"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@repo/ui/button";
import styles from "../page.module.css";

// 模拟用户偏好数据
const userPreferences = {
  userId: "user123",
  interests: ["电子产品", "数码配件", "智能家居"],
  browsingHistory: ["手机", "耳机", "充电器"],
  purchaseHistory: ["无线耳机", "充电宝"]
};

// 模拟商品数据
const mockProducts = [
  { id: 1, name: "iPhone 15 Pro", price: 7999, category: "电子产品", rating: 4.9, sales: 1234, image: "📱" },
  { id: 2, name: "AirPods Pro", price: 1899, category: "数码配件", rating: 4.8, sales: 2341, image: "🎧" },
  { id: 3, name: "MacBook Air", price: 8999, category: "电子产品", rating: 4.7, sales: 567, image: "💻" },
  { id: 4, name: "智能手表", price: 2999, category: "数码配件", rating: 4.6, sales: 890, image: "⌚" },
  { id: 5, name: "无线充电器", price: 299, category: "数码配件", rating: 4.5, sales: 1234, image: "🔋" },
  { id: 6, name: "蓝牙音箱", price: 599, category: "数码配件", rating: 4.4, sales: 678, image: "🔊" },
  { id: 7, name: "智能摄像头", price: 399, category: "智能家居", rating: 4.3, sales: 456, image: "📹" },
  { id: 8, name: "智能灯泡", price: 99, category: "智能家居", rating: 4.2, sales: 789, image: "💡" },
  { id: 9, name: "平板电脑", price: 3999, category: "电子产品", rating: 4.1, sales: 345, image: "📱" },
  { id: 10, name: "机械键盘", price: 499, category: "数码配件", rating: 4.0, sales: 567, image: "⌨️" },
  { id: 11, name: "游戏鼠标", price: 299, category: "数码配件", rating: 4.1, sales: 432, image: "🖱️" },
  { id: 12, name: "显示器", price: 1299, category: "电子产品", rating: 4.2, sales: 234, image: "🖥️" },
];

// 模拟API调用 - 根据用户偏好推荐商品
const fetchPersonalizedProducts = async (page: number, pageSize: number = 6) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500));
  
  // 根据用户偏好排序商品
  const sortedProducts = mockProducts.sort((a, b) => {
    const aScore = userPreferences.interests.includes(a.category) ? 2 : 1;
    const bScore = userPreferences.interests.includes(b.category) ? 2 : 1;
    return bScore - aScore;
  });
  
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  
  return {
    products: sortedProducts.slice(start, end),
    total: mockProducts.length,
    hasMore: end < mockProducts.length
  };
};

export default function ProductList() {
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [userInfo, setUserInfo] = useState(userPreferences);

  // 加载商品数据
  const loadProducts = useCallback(async (pageNum: number, append: boolean = false) => {
    setLoading(true);
    try {
      const result = await fetchPersonalizedProducts(pageNum);
      
      if (append) {
        setProducts(prev => [...prev, ...result.products]);
      } else {
        setProducts(result.products);
      }
      
      setHasMore(result.hasMore);
    } catch (error) {
      console.error("加载商品失败:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadProducts(1);
  }, [loadProducts]);

  // 加载更多
  const loadMore = () => {
    if (!loading && hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      loadProducts(nextPage, true);
    }
  };

  // 刷新推荐
  const refreshRecommendations = () => {
    setPage(1);
    loadProducts(1);
  };

  return (
    <div className={styles.productListContainer}>
      {/* 用户信息和个性化提示 */}
      <div className={styles.personalizationInfo}>
        <div className={styles.userInfo}>
          <span className={styles.userId}>用户: {userInfo.userId}</span>
          <span className={styles.interests}>
            兴趣: {userInfo.interests.join(", ")}
          </span>
        </div>
        <Button 
          appName="web" 
          className={styles.refreshButton}
          onClick={refreshRecommendations}
        >
          🔄 刷新推荐
        </Button>
      </div>

      {/* 商品网格 */}
      <div className={styles.productGrid}>
        {products.map((product) => (
          <div key={product.id} className={styles.productCard}>
            <div className={styles.productImage}>
              <div className={styles.imagePlaceholder}>
                {product.image}
              </div>
            </div>
            <div className={styles.productInfo}>
              <h3>{product.name}</h3>
              <div className={styles.category}>{product.category}</div>
              <div className={styles.priceInfo}>
                <span className={styles.price}>¥{product.price}</span>
              </div>
              <div className={styles.productMeta}>
                <span className={styles.rating}>⭐ {product.rating}</span>
                <span className={styles.sales}>已售 {product.sales}</span>
              </div>
              <div className={styles.productActions}>
                <Button appName="web" className={styles.viewButton}>
                  查看详情
                </Button>
                <Button appName="web" className={styles.buyButton}>
                  立即购买
                </Button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 加载更多按钮 */}
      {hasMore && (
        <div className={styles.loadMoreSection}>
          <Button 
            appName="web" 
            className={styles.loadMoreButton}
            onClick={loadMore}
            disabled={loading}
          >
            {loading ? "加载中..." : "加载更多"}
          </Button>
        </div>
      )}

      {/* 加载状态 */}
      {loading && (
        <div className={styles.loadingIndicator}>
          <div className={styles.spinner}></div>
          <p>正在为您推荐个性化商品...</p>
        </div>
      )}

      {/* 没有更多数据 */}
      {!hasMore && products.length > 0 && (
        <div className={styles.noMoreData}>
          <p>🎉 已加载全部推荐商品</p>
        </div>
      )}
    </div>
  );
}
